package com.shell.customer.base.service.impl;

import com.shell.bee.persistence.service.impl.PersistentServiceImpl;
import com.shell.customer.base.dao.CusLvlDao;
import com.shell.customer.base.service.CusLvlService;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusLvl;
import com.shell.customer.po.CusRec;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("cusLvlService")
public class CusLvlServiceImpl extends PersistentServiceImpl<CusLvl> implements CusLvlService {
	@Autowired
	private CusGrpService cusGrpService;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private CusLvlDao cusLvlDao;

	public void setCusLvl(CusInvt cusInvt) {
		if (!"SUPPLIER".equals(cusInvt.getInviteeCusType())) {
			return;
		}
		CusGrp grp = (CusGrp) this.cusGrpService.selectByKey(cusInvt.getInviterId());
		String grpId = "";
		int level = 1;
		if (grp != null) {
			grpId = grp.getGrpId();
		} else {
			CusRec invtCus = (CusRec) this.cusRecService.selectByKey(cusInvt.getInviterId());
			CusLvl parentLvl = new CusLvl();
			parentLvl.setGrpId(invtCus.getGrpId());
			parentLvl.setCusId(invtCus.getCusId());
			parentLvl = (CusLvl) selectOne(parentLvl);
			if (parentLvl != null) {
				level = parentLvl.getCusLvl().intValue() + 1;
			}
			grpId = invtCus.getGrpId();
		}
		CusLvl queryLvl = new CusLvl();
		queryLvl.setGrpId(grpId);
		queryLvl.setCusId(cusInvt.getInviteeId());
		CusLvl cusLvl = (CusLvl) selectOne(queryLvl);
		if (cusLvl == null) {
			cusLvl = new CusLvl();
			cusLvl.setGrpId(grpId);
			cusLvl.setCusId(cusInvt.getInviteeId());
			cusLvl.setCusLvl(Integer.valueOf(level));
			save(cusLvl);
		}
	}

	public List<CusLvl> getGrpCusLvl(String grpId) {
		return this.cusLvlDao.getGrpCusLvl(grpId);
	}
}